package com.sailors.common.task.provider.infra.design.common.rest;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

public class PageUtils {
    public static final long DEFAULT_PAGE_NUMBER = 1;
    public static final long MIN_PAGE_NUMBER = 1;
    public static final long MAX_PAGE_NUMBER = 100;

    public static final long DEFAULT_PAGE_SIZE = 10;
    public static final long MIN_PAGE_SIZE = 1;
    public static final long MAX_PAGE_SIZE = 1000;

    public static <T> Page<T> toPage(PageReq param) {
        if (param == null) {
            return new Page<>(DEFAULT_PAGE_NUMBER, DEFAULT_PAGE_SIZE);
        }

        long pageNumber = Optional.ofNullable(param.getPageNumber()).orElse(DEFAULT_PAGE_NUMBER);
        pageNumber = Math.min(Math.max(pageNumber, MIN_PAGE_NUMBER), MAX_PAGE_NUMBER);

        long pageSize = Optional.ofNullable(param.getPageSize()).orElse(DEFAULT_PAGE_SIZE);
        pageSize = Math.min(Math.max(pageSize, MIN_PAGE_SIZE), MAX_PAGE_SIZE);

        return new Page<>(pageNumber, pageSize);
    }

    public static <T, R> BasePageResponse<R> pageSuccess(Page<T> page, Function<? super T, ? extends R> mapper) {
        List<R> data = page.getRecords().stream().map(mapper).collect(Collectors.toList());
        return Bru.pageSuccess(page.getSize(), page.getCurrent(), page.getTotal(), data);
    }

    public static <T> BasePageResponse<T> pageSuccess(Page<T> page) {
        List<T> records = page.getRecords();
        return Bru.pageSuccess(page.getSize(), page.getCurrent(), page.getTotal(), records);
    }
}
